package com.sqly.doc.menu.qianyue;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Environment;
import android.support.annotation.IdRes;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.ihidea.multilinechooselib.MultiLineChooseLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CheckBoxAdapter;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.menu.camera.CameraChoose;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.pojo.ServicePackage;
import com.sqly.doc.pojo.SignUp;
import com.sqly.doc.pojo.Team;
import com.sqly.doc.pojo.TeamMember;
import com.sqly.doc.util.Constants;
import com.sqly.doc.util.CreateBitmap;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.LvHeightUtil;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.Url;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.util.WriteActivity;
import com.sqly.doc.view.CustomDatePicker;
import com.sqly.doc.view.StringUtils;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cxy.com.validate.IValidateResult;
import cxy.com.validate.Validate;
import cxy.com.validate.annotation.Index;
import cxy.com.validate.annotation.NotNull;
import cxy.com.validate.annotation.RE;
import cz.msebera.android.httpclient.Header;

//import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2017-12-05.
 */

public class qianyue_add extends MyBaseActivity {
    //标题
    TextView title, uname,fwnrid;

    @Index(1)
    @NotNull(msg = "签约机构不能为空")
    @Bind(R.id.qyjg)
    TextView qyjg;

    @Index(2)
    @NotNull(msg = "签约时间不能为空")
    @Bind(R.id.qysj)
    TextView qysj;

    @Index(3)
    @NotNull(msg = "服务团队不能为空")
    @Bind(R.id.fwtd)
    TextView fwtd;

    @Index(4)
    @NotNull(msg = "主管医生不能为空")
    @Bind(R.id.zgys)
    TextView zgys;

    @Index(5)
    @RE(re = Constants.LXDH_REGEXP, msg = "请输入正确的医生联系电话")
    @Bind(R.id.yslxdh)
    EditText yslxdh;

    @Index(6)
    @NotNull(msg = "居民姓名不能为空")
    @Bind(R.id.jmxm)
    TextView jmxm;

    @Index(7)
    @NotNull(msg = "家庭住址不能为空")
    @Bind(R.id.jtzz)
    TextView jtzz;

    @Index(8)
    @RE(re = Constants.LXDH_REGEXP, msg = "请输入正确的本人电话")
    @Bind(R.id.jmlxdh)
    EditText jmlxdh;

    @Index(9)
    @RE(re = Constants.LXDH_REGEXP, msg = "请输入正确的联系人电话")
    @Bind(R.id.jmlxrdh)
    EditText jmlxrdh;

    @Index(10)
    @NotNull(msg = "请选择服务内容")
    @Bind(R.id.fwnrname)
    TextView fwnrname;

    @Bind(R.id.bddh1)ImageView bddh1;
    @Bind(R.id.bddh2)ImageView bddh2;
    @Bind(R.id.jhsytsjt)RadioGroup jhsytsjt;
    @Bind(R.id.dsznscsw)RadioGroup dsznscsw;
    @Bind(R.id.ncjdlkpkrk)RadioGroup ncjdlkpkrk;
    @Bind(R.id.cxdbwbrk)RadioGroup cxdbwbrk;

    ListView listView,fwblistView;//团队列表
    Spinner qynx;
    private List<String> qynxdata = new ArrayList<>();

    MultiLineChooseLayout fwb;//服务包内容
    private List<String> fwbdata = new ArrayList<>();

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    List<TeamMember> memberListInTeam;//医疗团队成员
    List<ServicePackage> servicePackageList  = new ArrayList<ServicePackage>();//医疗团队成员
    SignUp obj;
    JuMin juMin;
    Team teamObj;
    Context con = qianyue_add.this;
    ZLoadingDialog dialog;
    ImageView brqm, xcqm;
    String brqmpic = "" ,xcqmpic ="";
    int pageNum1 = 1;// 无关键字页数

    ImageView xcpaizhao;
    TextView pz_record_id,jmqm_record_id;
    boolean pzChange = false;
    String url = "";
    LinearLayout back;
    private CustomDatePicker customDatePicker;

    @Override
    protected void initUI() {
        setContentView(R.layout.qianyue_add);
        ButterKnife.bind(this);
        Validate.reg(this);
        juMin = (JuMin) getIntent().getExtras().getSerializable("juMin");
        obj = new SignUp();
        if (getIntent().getStringExtra("type").equals("edit")) {
            url = HttpUrl.SignEidt;
        } else {
            url = HttpUrl.SignAdd;
        }
        init();
        if(!StringUtils.isEmpty(juMin.getImg())){
            //ImageLoader.getInstance().displayImage(Url.img_url()+juMin.getImg(),brqm);
            ImageLoader.getInstance().displayImage(Url.newStaticurl(SharedPreferencesUtils.getParam(con, "token", "").toString(), "2" ,juMin.getImg()),brqm);
        }
        if(!StringUtils.isEmpty(juMin.getImg2())){
            //ImageLoader.getInstance().displayImage(Url.img_url()+juMin.getImg2(),xcqm);
            ImageLoader.getInstance().displayImage(Url.newStaticurl(SharedPreferencesUtils.getParam(con, "token", "").toString(), "2" ,juMin.getImg2()),xcqm);
        }
    }
    private void init(){
        obj.setContract_age("1");
        listView = (ListView) findViewById(R.id.listView);
        fwblistView = (ListView) findViewById(R.id.fwblistView);
        final String jmId = SharedPreferencesUtils.getParam(con, "uid", "").toString(),
                jmName = SharedPreferencesUtils.getParam(con, "uname", "").toString();
        brqm = (ImageView) findViewById(R.id.brqm);
        if (obj != null && !StringUtils.isEmpty(juMin.getBrqm())) {
            brqmpic = juMin.getBrqm();
            Log.i("tppath",Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg");
            brqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
        }
        brqm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, WriteActivity.class)
                        .putExtra("cardnum", juMin.getCARDNUM())
                        .putExtra("tabId", null==obj.getUid()||"".equals(obj.getUid()) ? "noid" : obj.getUid())
                        .putExtra("tabType", "qianyue")
                        .putExtra("imageType", "img")
                        .putExtra("class","qianyue_add.class"), 9);
            }
        });

        xcqm = (ImageView) findViewById(R.id.xcqm);
        if (obj != null && !StringUtils.isEmpty(juMin.getXcqm())) {
            xcqmpic = juMin.getXcqm();
            xcqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + xcqmpic + ".jpg"));
        }
        xcqm.setOnClickListener(new CustomerListener());

        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        if (juMin != null && !StringUtils.isEmpty(juMin.getYldwname())) {
            qyjg.setText(juMin.getYldwname());
        }
        if (juMin != null && !StringUtils.isEmpty(juMin.getParty_a_team_name())) {
            fwtd.setText(juMin.getParty_a_team_name());
            obj.setParty_a_team_name(juMin.getParty_a_team_name());
            obj.setParty_a_team_id(juMin.getParty_a_team_name());
        }
        fwtd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(con, choose_team.class).putExtra("cname", "qianyue_add.class"), 11);
            }
        });
        if(getIntent().getStringExtra("type").equals("edit")) {
            if (juMin != null && !StringUtils.isEmpty(juMin.getParty_a_team_id())) {
                getMemberByTeam(juMin.getParty_a_team_id());
            }
        }
        if (juMin != null && !StringUtils.isEmpty(juMin.getSignuptime())) {
            qysj.setText(DateConvert.dateToString(DateConvert.toDate(juMin.getSignuptime(), DateConvert.YMD), DateConvert.YMD)+"");
        }else{
            qysj.setText(df.format(new Date()));
        }

        qysj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        qysj.setText(time.split(" ")[0]);
                    }
                }, DateConvert.getCustomDatePickerStartRq(), DateConvert.getCustomDatePickerEndRq()); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                if (juMin != null && !StringUtils.isEmpty(juMin.getSignuptime())) {
                    customDatePicker.show(DateConvert.dateToString(DateConvert.toDate(juMin.getSignuptime(), DateConvert.YMD), DateConvert.YMD));
                }else {
                    customDatePicker.show(DateConvert.getCustomDatePickerNowRq());
                }
            }
        });
        if (juMin != null && !StringUtils.isEmpty(juMin.getParty_a_contractor_name())) {
            zgys.setText(juMin.getParty_a_contractor_name());
        }else{
            zgys.setText(jmName);
        }
        if (juMin != null && !StringUtils.isEmpty(juMin.getParty_a_tel())) {
            yslxdh.setText(juMin.getParty_a_tel());
        }else {
            yslxdh.setText(SharedPreferencesUtils.getParam(con, "phone", "").toString());
        }

        if (juMin != null && !StringUtils.isEmpty(juMin.getXINGMING())) {
            jmxm.setText(juMin.getXINGMING());
        }
        //现场拍照
        xcpaizhao = (ImageView) findViewById(R.id.xcpaizhao);
        xcpaizhao.setOnClickListener(new CustomerListener());
        //现场拍照照片id
        pz_record_id = (TextView) findViewById(R.id.pz_record_id);
        if(obj != null && !StringUtils.isEmpty(obj.getImg2())) {
            String[] img2Arr =obj.getImg2().split("/");
            if(null !=img2Arr && img2Arr.length>1){
                Log.i("img2Arr[1]",img2Arr[1]);
                pz_record_id.setText(img2Arr[1]);
            }
        }
        jmqm_record_id= (TextView) findViewById(R.id.jmqm_record_id);
        if(obj != null && !StringUtils.isEmpty(obj.getImg())) {
            String[] img2Arr =obj.getImg().split("/");
            if(null !=img2Arr && img2Arr.length>1){
                jmqm_record_id.setText(img2Arr[1]);
            }
        }

        if (juMin != null && !StringUtils.isEmpty(juMin.getCZDZ())) {
            jtzz.setText(juMin.getCZDZ());
        }
        if (juMin != null && !StringUtils.isEmpty(juMin.getLXDH())) {
            jmlxdh.setText(juMin.getLXDH());
        }
        bddh1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!StringUtils.isEmpty(jmlxdh.getText().toString())){
                    SweetAlertDialogUtil.callDialog(con,"确认提示", "您确认拨打居民本人电话吗？", "确定", jmlxdh.getText().toString());
                }
            }
        });
        if (juMin != null && !StringUtils.isEmpty(juMin.getLXRDH())) {
            jmlxrdh.setText(juMin.getLXRDH());
        }
        bddh2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!StringUtils.isEmpty(jmlxrdh.getText().toString())){
                    SweetAlertDialogUtil.callDialog(con,"确认提示", "您确认拨打居民联系人电话吗？", "确定", jmlxrdh.getText().toString());
                }
            }
        });
        fwnrid = (TextView) findViewById(R.id.fwnrid);
        if (juMin != null && !StringUtils.isEmpty(juMin.getFwnrids())) {
            fwnrid.setText(juMin.getFwnrids());
        }
        if (juMin != null && !StringUtils.isEmpty(juMin.getFwnrnames())) {
            fwnrname.setText(juMin.getFwnrnames());
        }
        fwnrname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String oldfwnrids = "", oldfwnrnames = "";
                if (juMin != null && !StringUtils.isEmpty(juMin.getFwnrids())) {
                    oldfwnrids = juMin.getFwnrids();
                    oldfwnrnames = juMin.getFwnrnames();;
                }
                startActivityForResult(new Intent(con, choose_servicepack.class)
//                        .putExtra("oldfwnrids", oldfwnrids).putExtra("oldfwnrnames", oldfwnrnames)
                        .putExtra("cname", "qianyue_add.class"), 12);
            }
        });
        ///签约年限
        qynx = (Spinner) findViewById(R.id.qynx);
        qynxdata.add("1");
//        qynxdata.add("2");
//        qynxdata.add("3");
        qynx.setAdapter(new CommonAdapter<String>(con, qynxdata, R.layout.sp_item) {
            @Override
            public void convert(ViewHolder helper, String item) {
                helper.setText(R.id.name, item);
            }
        });
        qynx.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                obj.setContract_age((position + 1) + "");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if (juMin != null && !StringUtils.isEmpty(juMin.getJhsytsjt())) {
            switch (Integer.parseInt(juMin.getJhsytsjt())) {
                case 1:
                    jhsytsjt.check(R.id.jhsytsjt_shi);
                    break;
                case 0:
                    jhsytsjt.check(R.id.jhsytsjt_fou);
                    break;
            }
        } else {
            jhsytsjt.check(R.id.jhsytsjt_fou);
        }
        jhsytsjt.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (R.id.jhsytsjt_shi == checkedId)
                    juMin.setJhsytsjt("1");
                if (R.id.jhsytsjt_fou == checkedId)
                    juMin.setJhsytsjt("0");
            }
        });

        if (juMin != null && !StringUtils.isEmpty(juMin.getDsznscsw())) {
            switch (Integer.parseInt(juMin.getDsznscsw())) {
                case 1:
                    dsznscsw.check(R.id.dsznscsw_shi);
                    break;
                case 0:
                    dsznscsw.check(R.id.dsznscsw_fou);
                    break;
            }
        } else {
            dsznscsw.check(R.id.dsznscsw_fou);
        }
        dsznscsw.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (R.id.dsznscsw_shi == checkedId)
                    juMin.setDsznscsw("1");
                if (R.id.dsznscsw_fou == checkedId)
                    juMin.setDsznscsw("0");
            }
        });

        if (juMin != null && !StringUtils.isEmpty(juMin.getNcjdlkpkrk())) {
            switch (Integer.parseInt(juMin.getNcjdlkpkrk())) {
                case 1:
                    ncjdlkpkrk.check(R.id.ncjdlkpkrk_shi);
                    break;
                case 0:
                    ncjdlkpkrk.check(R.id.ncjdlkpkrk_fou);
                    break;
            }
        } else {
            ncjdlkpkrk.check(R.id.ncjdlkpkrk_fou);
        }
        ncjdlkpkrk.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (R.id.ncjdlkpkrk_shi == checkedId)
                    juMin.setNcjdlkpkrk("1");
                if (R.id.ncjdlkpkrk_fou == checkedId)
                    juMin.setNcjdlkpkrk("0");
            }
        });

        if (juMin != null && !StringUtils.isEmpty(juMin.getCxdbwbrk())) {
            switch (Integer.parseInt(juMin.getCxdbwbrk())) {
                case 1:
                    cxdbwbrk.check(R.id.cxdbwbrk_shi);
                    break;
                case 0:
                    cxdbwbrk.check(R.id.cxdbwbrk_fou);
                    break;
            }
        } else {
            cxdbwbrk.check(R.id.cxdbwbrk_fou);
        }
        cxdbwbrk.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (R.id.cxdbwbrk_shi == checkedId)
                    juMin.setCxdbwbrk("1");
                if (R.id.cxdbwbrk_fou == checkedId)
                    juMin.setCxdbwbrk("0");
            }
        });

        fwb = (MultiLineChooseLayout) findViewById(R.id.fwnr);
        //getServicePack();
        //标题
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("签约");
        back = (LinearLayout)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(pzChange){
                    SweetAlertDialogUtil.WarningDialogHaveCancelAndConfirm(con,"你确认不保存数据更新吗？","现场拍照已经采集，请注意点击“保存”","确定", "返回");
                }else {
                    finish();
                }
            }
        });
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Validate.check(con, new IValidateResult() {
                    @Override
                    public void onValidateSuccess() {
                        saveData(jmId, jmName);
                    }

                    @Override
                    public void onValidateError(String msg, View view) {
                        view.setFocusable(true);
                        //Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();
                        SweetAlertDialogUtil.WarningDialog(con, "提示", msg);
                    }

                    @Override
                    public Animation onValidateErrorAnno() {
//                        return ValidateAnimation.horizontalTranslate();
                        return null;
                    }
                });
            }
        });
    }

    /***
     * 签约提交方法
     * @param jmId
     * @param jmName
     */
    private void saveData(final String jmId, String jmName){
        String fwbs = fwnrid.getText().toString();
        if(null == fwbs || "".equals(fwbs)){
            SweetAlertDialogUtil.WarningDialog(con, "提示", "请选择服务内容");
        }else if ("1".equals(SharedPreferencesUtils.getParam(con, "jmqm", "0").toString()) && jmqm_record_id.getText().toString().equals("noid")) {
            SweetAlertDialogUtil.WarningDialog(con, "提示", "家属或本人签名不能为空");
        }else if ("1".equals(SharedPreferencesUtils.getParam(con, "xcpz", "0").toString()) && pz_record_id.getText().toString().equals("noid")) {
            SweetAlertDialogUtil.WarningDialog(con, "提示", "现场拍照不能为空");
        }else {
            obj.setTbtime(qysj.getText().toString());
            obj.setParty_a_contractor_id(jmId);
            obj.setParty_a_contractor_name(jmName);
            if(getIntent().getStringExtra("type").equals("edit")) {
                if(null == teamObj || "".equals(teamObj.getTid())) {
                    obj.setParty_a_team_id(juMin.getParty_a_team_id());
                    obj.setParty_a_team_name(juMin.getParty_a_team_name());
                }
            }else{
                obj.setParty_a_team_id(teamObj.getTid());
                obj.setParty_a_team_name(teamObj.getName());
            }
            obj.setParty_a_tel(yslxdh.getText().toString());
            obj.setParty_b_tel(jmlxdh.getText().toString());
            obj.setParty_b_other_tel(jmlxrdh.getText().toString());
            obj.setParty_b_addr(jtzz.getText().toString());
            obj.setParty_b_id(juMin.getJKDAH());
            obj.setParty_b_name(juMin.getXINGMING());
            obj.setPz_record_id(pz_record_id.getText().toString());
            obj.setService_pack_id(fwbs);
            obj.setJhsytsjt(juMin.getJhsytsjt());
            obj.setDsznscsw(juMin.getDsznscsw());
            obj.setNcjdlkpkrk(juMin.getNcjdlkpkrk());
            obj.setCxdbwbrk(juMin.getCxdbwbrk());
            if (NetWorkUtils.isNetworkConnected(con)) {
                RequestParams ps = new RequestParams();
                ps.add("type", "2");
                ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                ps.add("entity.contract_age", obj.getContract_age());
                ps.add("entity.party_a_contractor_id", obj.getParty_a_contractor_id());
                ps.add("entity.party_a_contractor_name", obj.getParty_a_contractor_name());
                ps.add("entity.party_a_team_id", obj.getParty_a_team_id());
                ps.add("entity.party_a_team_name", obj.getParty_a_team_name());
                ps.add("entity.party_a_tel", obj.getParty_a_tel());
                ps.add("entity.party_b_tel", obj.getParty_b_tel());
                ps.add("entity.party_b_other_tel", obj.getParty_b_other_tel());
                ps.add("entity.party_b_addr", obj.getParty_b_addr());
                ps.add("entity.party_b_id", obj.getParty_b_id());
                ps.add("entity.party_b_name", obj.getParty_b_name());
                ps.add("entity.tbtime", obj.getTbtime());
                ps.add("entity.jhsytsjt", obj.getJhsytsjt());
                ps.add("entity.dsznscsw", obj.getDsznscsw());
                ps.add("entity.ncjdlkpkrk", obj.getNcjdlkpkrk());
                ps.add("entity.cxdbwbrk", obj.getCxdbwbrk());
                ps.add("service_pack_id", obj.getService_pack_id());

                ps.add("pz_record_id", obj.getPz_record_id());
                ps.add("jmqm_record_id", jmqm_record_id.getText().toString());
                ps.add("ysqm_record_id", jmqm_record_id.getText().toString());
//                qianyue_add.super.ImageUploadOperate(null, brqmpic, ps);
                if (getIntent().getStringExtra("type").equals("edit")) {
                    ps.add("entity.id", juMin.getSignupid());
                }
                UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        dialog.show();
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                        String content = new String(response);
                        dialog.dismiss();
                        RetMsg ret = JSON.parseObject(content, RetMsg.class);
                        if (ret.getCode().equals("200")) {
                            MyToastUtil.ShowToast(con, "保存成功");
                            finish();
                        }else{
                            MyToastUtil.ShowToast(con, ret.getInfo());
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                        dialog.dismiss();
                        MyToastUtil.ShowToast(con, "网络连接失败");
                    }
                });
            } else{
                MyToastUtil.ShowToast(con, "网络连接失败");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else if (requestCode == 11) {
            teamObj = (Team) data.getExtras().getSerializable("teamObj");
            qyjg.setText(teamObj.getNameD());
            fwtd.setText(teamObj.getName());
            obj.setParty_a_team_id(teamObj.getTid());
            obj.setParty_a_team_name(teamObj.getName());
            getMemberByTeam(teamObj.getTid());
        } else if (requestCode == 12) {
            String fwnrids = (String) data.getExtras().getString("fwnrids");
            String fwnrnames =(String) data.getExtras().getString("fwnrnames");
            fwnrid.setText(fwnrids);
            fwnrname.setText(fwnrnames);
        } else if (requestCode == 9) {
            String record_id = (String) data.getExtras().getString("record_id");
            jmqm_record_id.setText(record_id);
            byte[] bis = data.getByteArrayExtra("bitmap");
            Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
            brqm.setImageBitmap(bb);
            brqmpic = CreateBitmap.saveMyBitmap(bb);
        }else if(requestCode == 119){
            String img_record_id = (String) data.getExtras().getString("img_record_id");
            pz_record_id.setText(img_record_id);
            pzChange = true;
            byte[] bis = data.getByteArrayExtra("bitmap");
            Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
            xcqm.setImageBitmap(bb);
        }else if (requestCode == 1) {
            juMin = (JuMin) data.getExtras().getSerializable("juMin");
            jmxm.setText(juMin.getXINGMING());
            jtzz.setText(juMin.getHJDZ());
            String jmId = SharedPreferencesUtils.getParam(con, "uid", "").toString();
            List<SignUp> jlist = DataSupport.where("party_a_contractor_id = ? and party_b_id=?", jmId, juMin.getJKDAH()).find(SignUp.class);
            fwb.cancelAllSelectedItems();
            brqm.setImageResource(R.mipmap.qm);
            brqmpic = "";
            jmlxdh.setText(StringUtils.isEmpty(juMin.getLXDH()) ? "" : juMin.getLXDH());
            if (jlist.size() > 0) {
                Log.i("签约信息", jlist.size() + "" + jlist.get(0).getService_pack_id());
                obj = jlist.get(0);
                if (obj != null && !StringUtils.isEmpty(obj.getQm())) {
                    brqmpic = obj.getQm();
                    brqm.setImageBitmap(BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/" + brqmpic + ".jpg"));
                }
                List<ServicePackage> sl = DataSupport.findAll(ServicePackage.class);
                String[] serviceid = jlist.get(0).getService_pack_id().split(",");
                for (int i = 0; i < serviceid.length; i++) {
                    for (int j = 0; j < sl.size(); j++) {
                        if (serviceid[i].equals(sl.get(j).getSid()))
                            fwb.setIndexItemSelected(j);
                    }
                }
            } else {
                obj = new SignUp();
                fwb.cancelAllSelectedItems();
                brqm.setImageResource(R.mipmap.qm);
                brqmpic = "";
            }
        }
    }

    /**
     * 根据 teamId 查询团队成员列表数据
     * @param teamId
     */
    private void getMemberByTeam(String teamId){
        //团队成员
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page", pageNum1 + "");
        ps.add("teamid", teamId);
        ps.add("pageSize","100");
        UserClient.get(HttpUrl.GetMemberInTeam, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (pageNum1 == 1)
                        memberListInTeam = new ArrayList<TeamMember>();
                    List<TeamMember> tempList = JSON.parseArray(ret.getRd(), TeamMember.class);
                    for (int i = 0; i < tempList.size(); i++) {
                        memberListInTeam.add(tempList.get(i));
                    }
                    listView.setAdapter(new CommonAdapter<TeamMember>(con, memberListInTeam, R.layout.qy_team_item) {
                        @Override
                        public void convert(ViewHolder helper, TeamMember item) {
                            helper.setText(R.id.name, item.getMember_name());
                            helper.setText(R.id.tdmc, item.getName());
                            helper.setText(R.id.jgmc, item.getNameD());
                        }
                    });
                    LvHeightUtil.setListViewHeightBasedOnChildren(listView);
                }
            }
        });
    }

    /***
     * 查询服务包数据
     */
    private void getServicePack(){
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("page",  "1");
        ps.add("pageSize","100");
        UserClient.get(HttpUrl.GetSpByYsOrJmPagelst, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<ServicePackage> tempList = JSON.parseArray(ret.getList(), ServicePackage.class);
                    JSONArray jsArr = JSON.parseArray(ret.getList());
                    for (int i = 0; i < jsArr.size(); i++) {
                        JSONObject j = jsArr.getJSONObject(i);
                        tempList.get(i).setSid(j.getString("id"));
                        if(null !=j.getString("yxz") && !"".equals(j.getString("yxz")) && "1".equals(j.getString("yxz"))){
                            tempList.get(i).setChecked(true);
                        }else{
                            tempList.get(i).setChecked(false);
                        }

                    }
                    for (int i = 0; i < tempList.size(); i++) {
                        fwbdata.add(tempList.get(i).getName());
                    }
                    fwb.setList(fwbdata);

                    for (int i = 0; i < tempList.size(); i++) {
                        servicePackageList.add(tempList.get(i));
                    }
                    final Map<String, String> mapTemp = new HashMap<String, String>();
                    final CheckBoxAdapter myAdapter = new CheckBoxAdapter(con);
                    myAdapter.setDatas(servicePackageList);
                    fwblistView.setAdapter(myAdapter);
                    fwblistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        int currentNum = -1;
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                            ServicePackage sp = servicePackageList.get(position);
                            if(sp.isChecked()){
                                sp.setChecked(false);
                                if(null != mapTemp.get(sp.getSid())) {
                                    mapTemp.remove(sp.getSid());
                                }
                            }else {
                                sp.setChecked(true);
                                mapTemp.put(sp.getSid(), sp.getName());
                            }
                            String idKey = "-1", nameValue ="";
                            Iterator<Map.Entry<String,String>> iter = mapTemp.entrySet().iterator();
                            String fwnrids = "";
                            String fwnrnames = "";
                            while(iter.hasNext()){
                                Map.Entry<String,String> entry = iter.next();
                                idKey = entry.getKey(); nameValue = entry.getValue();
                                fwnrids = idKey+","+fwnrids;
                                fwnrnames =  nameValue+","+fwnrnames;
                            }
                            if(null != fwnrids && fwnrids.length()>1 && fwnrids.endsWith(",")){
                                fwnrids = fwnrids.substring(0, fwnrids.length()-1);
                            }
                            if(null != fwnrnames && fwnrnames.length()>1 && fwnrnames.endsWith(",")){
                                fwnrnames = fwnrnames.substring(0, fwnrnames.length()-1);
                            }
                            fwnrid.setText(fwnrids);
                            fwnrname.setText(fwnrnames);
                            myAdapter.notifyDataSetChanged();//刷新adapter
                        }
                    });
                    LvHeightUtil.setListViewHeightBasedOnChildren(fwblistView);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Validate.unreg(this);
    }

    @Override
    protected void initListener() {
//        jmxm.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivityForResult(new Intent(con, choose_user.class).putExtra("cname", "qianyue_add.class").putExtra("type", "wqy"), 1);
//            }
//        });
//        String  xzgly = SharedPreferencesUtils.getParam(con, "xzgly", "0").toString();
//        if(null != xzgly && "0".equals(xzgly)) {
//
//        }
    }

    class CustomerListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            if(getIntent().getStringExtra("type").equals("edit")){
                if(obj != null && StringUtils.isEmpty(obj.getParty_a_team_name())) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "选择服务团队信息后才能现场拍照");
                }else {
                    Intent intent = new Intent(con, CameraChoose.class)
                            .putExtra("type", "edit")
                            .putExtra("cardnum", juMin.getCARDNUM())
                            .putExtra("tabId", null==obj.getUid()||"".equals(obj.getUid()) ? "noid" : obj.getUid())
                            .putExtra("tabType", "qianyue")
                            .putExtra("class", "qianyue_add.class");
                    startActivityForResult(intent, 119);
                }
            }else {
                if (obj != null && StringUtils.isEmpty(obj.getParty_a_team_name())) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "选择服务团队信息后才能现场拍照");
                } else {
                    Intent intent = new Intent(con, CameraChoose.class)
                            .putExtra("type", "edit")
                            .putExtra("cardnum", juMin.getCARDNUM())
                            .putExtra("tabId", null == obj.getUid() || "".equals(obj.getUid()) ? "noid" : obj.getUid())
                            .putExtra("tabType", "qianyue")
                            .putExtra("class", "qianyue_add.class");
                    startActivityForResult(intent, 119);
                }
            }
        }
    }
}
